#!/usr/bin/env python
import numpy as np
import sys
from astropy.table import Table

if sys.argv[1] == 'uv':
    ratio = 0.7683
if sys.argv[1] == 'op':
    ratio = 0.75
if sys.argv[1] == 'ir':
    ratio = 0.73
files = ['low_h1/mtf_result_low_h1.log','low_v1/mtf_result_low_v1.log','low_h2/mtf_result_low_h2.log','low_v2/mtf_result_low_v2.log',\
'high_h1/mtf_result_high_h1.log','high_v1/mtf_result_high_v1.log','high_h2/mtf_result_high_h2.log','high_v2/mtf_result_high_v2.log']
tab = Table()
data = []
for i in range(len(files)):
    f = open(files[i],'r')
    lines = f.readlines()
    mtf = []
    for j in range(len(lines)-1):
        mtf.append(float(lines[j+1].split(',')[2]))
    data.append(np.median(np.array(mtf)))
tab['pos'] = np.array(['1','2','mean','worst'])
tab['low_h'] = np.round(np.array([data[0],data[2],(data[0]+data[2])/2,np.min(np.array([data[0],data[2]]))])/ratio,4)
tab['low_v'] = np.round(np.array([data[1],data[3],(data[1]+data[3])/2,np.min(np.array([data[1],data[3]]))])/ratio,4)
tab['high_h'] = np.round(np.array([data[4],data[6],(data[4]+data[6])/2,np.min(np.array([data[4],data[6]]))])/ratio,4)
tab['high_v'] = np.round(np.array([data[5],data[7],(data[5]+data[7])/2,np.min(np.array([data[5],data[7]]))])/ratio,4)
inhomo1 = 1-np.min(np.array([data[0],data[1]]))/np.max(np.array([data[0],data[1]]))
inhomo2 = 1-np.min(np.array([data[2],data[3]]))/np.max(np.array([data[2],data[3]]))
tab['inhomo'] = np.round(np.array([inhomo1,inhomo2,np.mean(np.array([inhomo1,inhomo2])),np.max(np.array([inhomo1,inhomo2]))]),4)
degrad_h = np.array([1-data[4]/data[0],1-data[6]/data[2]])
tab['degrad_h'] = np.round(np.array([degrad_h[0],degrad_h[1],np.mean(degrad_h),np.max(degrad_h)]),4)
degrad_v = np.array([1-data[5]/data[1],1-data[7]/data[3]])
tab['degrad_v'] = np.round(np.array([degrad_v[0],degrad_v[1],np.mean(degrad_v),np.max(degrad_v)]),4)
tab.write("mtf_result.tab",format='ipac',overwrite=True)
